#include <stdio.h>

// Function to swap two elements
void swap(int* a, int* b) {
    // Temporary variable to hold the value of *a
    int t = *a;
    // Assign the value of *b to *a
    *a = *b;
    // Assign the value of t (original *a) to *b
    *b = t;
}

// Function to partition the array into two parts, one with elements less than the pivot and the other with elements greater than the pivot
int partition(int arr[], int low, int high) {
    // Choose the last element as the pivot
    int pivot = arr[high];
    // Index of the smaller element
    int i = (low - 1);

    // Iterate through the array from low to high-1
    for (int j = low; j <= high - 1; j++) {
        // If the current element is less than or equal to the pivot
        if (arr[j] <= pivot) {
            // Increment the index of the smaller element
            i++;
            // Swap the current element with the element at the index of the smaller element
            swap(&arr[i], &arr[j]);
        }
    }
    // Swap the pivot element with the element at the index of the smaller element + 1
    swap(&arr[i + 1], &arr[high]);
    // Return the index of the pivot element
    return (i + 1);
}

// Function to perform quick sort on the array
void qs(int arr[], int low, int high) {
    // If the low index is less than the high index
    if (low < high) {
        // Partition the array and get the pivot index
        int pi = partition(arr, low, high);

        // Recursively sort the elements before the pivot
        qs(arr, low, pi - 1);
        // Recursively sort the elements after the pivot
        qs(arr, pi + 1, high);
    }
}

// Function to print the array
void printArray(int arr[], int size) {
    // Iterate through the array and print each element
    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);
    // Print a new line after the array
    printf("\n");
}

// Main function to test the quick sort algorithm
int main() {
    // Array to be sorted
    int arr[] = {10, 7, 8, 9, 1, 5};
    // Calculate the size of the array
    int n = sizeof(arr) / sizeof(arr[0]);
    // Print the original array
    printf("Original array: \n");
    printArray(arr, n);
    // Sort the array using quick sort
    qs(arr, 0, n - 1);
    // Print the sorted array
    printf("Sorted array: \n");
    printArray(arr, n);
    // Return 0 to indicate successful execution
    return 0;
}
